package com.example.shushiyunsst

import android.app.Application
import android.content.Context
import android.util.Log
import androidx.multidex.MultiDex
import com.alibaba.fastjson.parser.ParserConfig
import com.example.library_common.global.Latte
import com.example.library_common.utils.normalShortToast
import com.example.shushiyunsst.fragment.main.constant.CURRENT_DEVICE_TOKEN
import com.example.shushiyunsst.util.NotificationsUtils
import com.example.shushiyunsst.util.RequestInterceptor
import com.example.shushiyunsst.util.flutter_bridgt.EventChannelManager
import com.example.shushiyunsst.util.flutter_bridgt.EventChannelPlugin
import com.example.shushiyunsst.util.media.MediaControllerManager
import com.example.wallet.utils.Preference
import com.umeng.commonsdk.UMConfigure
import com.umeng.message.IUmengRegisterCallback
import com.umeng.message.MsgConstant
import com.umeng.message.PushAgent
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.embedding.engine.FlutterEngineCache
import io.flutter.embedding.engine.dart.DartExecutor

import okhttp3.logging.HttpLoggingInterceptor


class MyApp : Application() {

    companion object {
        const val TAG = "MyApp"
        const val KLINE_CHART_PANEL = "KLineChartPanel"
        const val K_Line_Chart_Land_Panel = "K_Line_Chart_Land_Panel"
        val flutterPage = listOf(
            KLINE_CHART_PANEL,
            K_Line_Chart_Land_Panel
        )

        var isAppUpData = false

        var instance: MyApp? = null
    }

    override fun attachBaseContext(base: Context?) {
        super.attachBaseContext(base)
        MultiDex.install(this)
    }

    override fun onCreate() {
        super.onCreate()
        instance = this

//        Web3jService.WEB3J_SERVICE_INSTANCE.getVersion()
//            .thenAccept {
//                if (BuildConfig.DEBUG) {
//                    Log.d("TAG", "onCreate: ${it.web3ClientVersion}")
//                }
//            }

        ParserConfig.global.isSafeMode = true
        ParserConfig.global.isAutoTypeSupport = true

        val httpLoggingInterceptor = HttpLoggingInterceptor()

        httpLoggingInterceptor.level = HttpLoggingInterceptor.Level.BODY

//        val mApiHost = if (BuildConfig.DEBUG) R.string.root_api_dev else R.string.root_api
        val mApiHost = if (BuildConfig.DEBUG) R.string.root_apt_dev_temp else R.string.root_apt_temp
        Latte.getConfigurator()
            .withInterceptor(RequestInterceptor())
            .withInterceptor(httpLoggingInterceptor)
            .withNativeApiHost(mApiHost)
            .withLoaderDelayed(0)
            .configure()

//        if (BuildConfig.DEBUG){
        try {
            //初始化友盟
            initYouMen(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }

        initFlutter(this)

        MediaControllerManager.init(this)

//
//
////            //初始化通知权限
////            initNotification(this)
//        }

    }

    private fun initFlutter(context: Context) {

        flutterPage.map {
            //在MyApplication中预先初始化Flutter引擎以提升Flutter页面打开速度
            val flutterEngine = FlutterEngine(context)

            //建立通信
            val eventChannelPlugin = EventChannelPlugin.registerWith(
                flutterEngine.dartExecutor,
                it
            )

            // 配置默认启动路由
            flutterEngine.navigationChannel.setInitialRoute(it)

            flutterEngine.dartExecutor.executeDartEntrypoint(
                DartExecutor.DartEntrypoint.createDefault()
            )

            // Cache the FlutterEngine to be used by FlutterActivity.
            FlutterEngineCache.getInstance().put(it, flutterEngine)

            EventChannelManager.instance?.putEventChannel(it, eventChannelPlugin)
        }

//        //在MyApplication中预先初始化Flutter引擎以提升Flutter页面打开速度
//        val flutterEngine = FlutterEngine(context)
//
//        //建立通信
//        val eventChannelPlugin = EventChannelPlugin.registerWith(
//            flutterEngine.dartExecutor,
//            KLINE_CHART_PANEL
//        )
//
//        // 配置默认启动路由
//        flutterEngine.navigationChannel.setInitialRoute(KLINE_CHART_PANEL)
//
//        flutterEngine.dartExecutor.executeDartEntrypoint(
//            DartExecutor.DartEntrypoint.createDefault()
//        )
//
//        // Cache the FlutterEngine to be used by FlutterActivity.
//        FlutterEngineCache.getInstance().put(KLINE_CHART_PANEL, flutterEngine)
//
//        EventChannelManager.instance?.putEventChannel(KLINE_CHART_PANEL,eventChannelPlugin)
    }

    private fun initNotification(context: Context) {
        if (!NotificationsUtils.isNotificationEnabled(context)) {
            NotificationsUtils.requestNotify(context)
            normalShortToast(context, "请打开通知权限")
//            Toast.makeText(context, "请打开通知权限", Toast.LENGTH_LONG).show()
        }
    }

    private fun initYouMen(context: Context) {
        val mAppKey = context.getString(R.string.m_app_push_key)

        val channelId = context.getString(R.string.push_channel_id)

        val messageSecret = context.getString(R.string.push_secret_key)

//        // 在此处调用基础组件包提供的初始化函数 相应信息可在应用管理 -> 应用信息 中找到 http://message.umeng.com/list/apps
//        // 参数一：当前上下文context；
//        // 参数二：应用申请的Appkey（需替换）；
//        // 参数三：渠道名称；
//        // 参数四：设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机；
//        // 参数五：Push推送业务的secret 填充Umeng Message Secret对应信息（需替换）
        UMConfigure.init(
            context,
            mAppKey,
            channelId,
            UMConfigure.DEVICE_TYPE_PHONE,
            messageSecret
        )

        //获取消息推送代理示例
        val mPushAgent = PushAgent.getInstance(context)

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.notificationPlaySound = MsgConstant.NOTIFICATION_PLAY_SERVER; //服务端控制声音
//        UMConfigure.setLogEnabled(true)

        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(object : IUmengRegisterCallback {
            override fun onSuccess(deviceToken: String) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Preference.HOLDER.addCustomAppProfile(CURRENT_DEVICE_TOKEN, deviceToken)
                Log.i(
                    TAG,
                    "注册成功：deviceToken：-------->  $deviceToken"
                )
            }

            override fun onFailure(s: String, s1: String) {
                Log.e(TAG, "注册失败：-------->  s:$s,s1:$s1")
            }
        })

    }
}